<template>
    <div class="send">

        <!--S无发红包权限区域-->
        <access v-if="!access"></access>
        <!--E无发红包权限区域-->

        <!--S金额统计-->
        <i-header
                v-if="red_id === 0"
                :total="total"
                :charge="charge"
                :pay="pay">
        </i-header>
        <!--E金额统计-->

        <!--S表单-->
        <div id="form" :style="{'padding-top':(red_id !== 0) ? '0' : ''}">
            <cube-scroll>

                <!--S表单-->
                <cube-form
                           ref="form"
                           :model="model"
                           :schema="schema"
                            @submit="submit"
                        >
                </cube-form>
                <!--E表单-->

            </cube-scroll>
        </div>
        <!--E表单-->

        <!--S追加红包-->
        <add-to-btn
                v-if="red_id !== 0 && is_edit"
                @click.native="showAddTo"
        >
        </add-to-btn>
            <!--S追加红包区域-->
            <add-to
                    :ratio="ratio"
                    :type="model.type"
                    :is_show="addTo.show"
                    :red_id="red_id"
                    :money="model.money"
                    @close="addTo.show = false"
                    @addTo="addToSuccess"
            >
            </add-to>
            <!--E追加红包区域-->
        <!--E追加红包-->

        <!--S发红包按钮-->
        <div id="send-button">
            <cube-button :disabled="publishing" @click="$refs.form.submit()">
                <template v-if="red_id">修改红包</template>
                <template v-else>发红包</template>
            </cube-button>
        </div>
        <!--E发红包按钮-->
    </div>
</template>

<script>
import store from '@/store'
import IHeader from './components/header'
import Access from "./components/access"
import FormCoupon from "./components/form-coupon"
import FormManage from "./components/form-manage"
import FormTime from "./components/form-time"
import FormArea from "./components/form-area"
import FormMedia from "@/form/form-meida"
import FormChoiceQuestion from "./components/form-choice-question"
import FormAnwserQuestion from "./components/form-answer-question"
import FormLink from "./components/form-link"
import AddToBtn from "./components/add-to-btn"
import AddTo from "./components/add-to"
export default {
    name: "send",
    data() {
      return {
          // 发红包权限
          access: 1,
          // 红包类型 default image video
          type: 'default',
          // 红包id 0=新增红包 其他=修改红包
          red_id: 0,
          // 是否为修改红包
          is_edit: false,
          // 手续费
          ratio:0.1,
          // 表单值
          model: {
              money:'',
              type:1,   //1=普通红包 2=拼手气红包
              send_coupon: 0, // 是否插入卡券
              coupon:"", // 投放的卡券id
              red_form: 0, // 0=关闭红包表单 1=开启红包表单
              red_form_id:"", //红包表单id
              number:1, // 红包数量
              title:'恭喜发财，大吉大利', // 红包标题
              media: [], // 图片红包数据,素材库id
              question:0, // 是否开启答题红包 0=不开启，1=问答题，2=选择题
              choice_question: ["",0,"",""],  // 选择题选项
              answer_question: ["",""],  // 问答题数据
              award:false, // 是否开启分享助力红包
              time_type: 1, //1=永久有效 2=时间限制
              time: {start:0,end:0}, // 红包开始结束时间
              area_type:0,  //0=不限制开红包区域，1=限制省，2=限制市区，3=限制区/县
              area: '',  //区域
              link: '' // 推广链接id
          },
          // 表单组件
          schema: {fields: []},
          // 红包发布中，服务器请求中
          publishing: false,
          // 红包相关配置
          setting: {},
          // 追加红包
          addTo: {
              show: false
          }
      }
    },
    watch: {
        // 红包类型
        "model.type" (value) {
            this.model.number = 1
            this.model.money = ''
            if(value === 1){
                this.schema.fields[0].label = '单个金额'
            } else {
                this.schema.fields[0].label = '红包总额'
            }
        },
        // 红包时间类型
        "model.time_type" (value) {
            this.toggleTimeForm(value !== 1)
        },
        // 是否开启红包卡券
        "model.send_coupon" () {
            this.pushCouponForm()
        },
        // 是否开启填报领取红包功能
        "model.red_form" () {
            this.pushRedForm()
        },
        // 区域限制类型
        "model.area_type" (value) {
            this.toggleAreaForm(value)
        },
        // 问答红包类型
        "model.question" () {
            this.toggleQuestionForm()
        }
    },
    computed: {
        // 红包总额
        total() {
            if(this.model.money === ''){
                return '0.00'
            }
            if(this.model.type === 1){
                //普通红包  总额=金额*红包数量
                return (parseFloat(this.model.money) * parseInt(this.model.number)).toFixed(2);
            }else{
                //手气红包  总额 = 金额;
                return parseFloat(this.model.money).toFixed(2);
            }
        },
        // 手续费
        charge(){
            return this.ratio === 0 ? '0.00' : (this.total * this.ratio).toFixed(2)
        },
        //支付总额
        pay(){
            return (parseFloat(this.total) + parseFloat(this.charge)).toFixed(2)
        },
        // 发送数据data
        send_data() {
            let {
                money,
                type,
                send_coupon,
                coupon,
                red_form,
                red_form_id,
                number,
                title,
                media,
                question,
                choice_question,
                answer_question,
                award,
                time_type,
                time,
                area_type,
                area,
                link
            } = this.model
            let send_data = {
                money,
                type,
                send_coupon,
                coupon,
                red_form,
                red_form_id,
                number,
                title,
                media,
                question,
                choice_question,
                answer_question,
                award: award ? 1 : 0,
                time_type,
                time,
                area_type,
                area,
                link,
                red_type: this.type,
                pay: this.pay,
                charge: this.charge
            }
            return send_data
        }
    },
    components: {
        IHeader,
        Access,
        AddToBtn,
        AddTo
    },
    created() {
        let {type, red_id} = this.$route.params
        this.type = type
        this.red_id = parseInt(red_id)
        if(this.red_id) {
            this.is_edit = true
        }
    },
    mounted() {
        // 发红包权限验证
        this.checkAccess()
            .then(() => {
                // 是否显示关注公众号弹窗
                if(this.access === 1) {
                    this.attentionDialog()
                }
            })
        // 获取红包相关配置
        this.getSetting()
        // 创建表单组件
        this.createForm()
        if(this.type === 'image'){
            this.pushImageRedForm()
        } else if(this.type === 'video'){
            this.pushVideoRedForm()
        }
        this.getRatio()
        if(this.red_id) this.getRed()
    },
    methods: {
        /**
         *获取红包信息
         */
        getRed(){
            return this.$get("red/get",{
                red_id: this.red_id
            })
                .then((res) => {
                    let {code, data} = res.data
                    if(code === 0) {
                        this.model = {
                            money: data.money,
                            type: parseInt(data.type),   //1=普通红包 2=拼手气红包
                            send_coupon: parseInt(data.send_coupon), // 是否插入卡券
                            coupon:parseInt(data.coupon), // 投放的卡券id
                            red_form: parseInt(data.red_form),
                            red_form_id: data.red_form_id,
                            number:parseInt(data.number), // 红包数量
                            title:data.title, // 红包标题
                            media: data.media, // 图片红包数据,素材库id
                            question:parseInt(data.question), // 是否开启答题红包 0=不开启，1=问答题，2=选择题
                            choice_question: data.choice_question,  // 选择题选项
                            answer_question: data.answer_question,  // 问答题数据
                            award:parseInt(data.award) === 1, // 是否开启分享助力红包
                            time_type: parseInt(data.time_type), //1=永久有效 2=时间限制
                            time: data.time, // 红包开始结束时间
                            area_type:parseInt(data.area_type),  //0=不限制开红包区域，1=限制省，2=限制市区，3=限制区/县
                            area: data.area,  //区域
                            link: parseInt(data.link) ? data.link : "" // 推广链接id
                        }
                        setTimeout(() => {
                            this.model.money = data.money
                            this.model.number = parseInt(data.number)
                            this.model.coupon = data.coupon
                            this.model.red_form_id = data.red_form_id
                            this.model.area = data.area
                        },100)
                    }
                });
        },
        /**
         * 获取红包手续费比例
         */
        getRatio() {
          this.$get("settingGain/find")
                .then((res) => {
                    let {code, data} = res.data
                    if(code === 0) {
                        if(this.type === "default") {
                            this.ratio = parseFloat(data.default_red_ratio / 100)
                        } else if(this.type === "image") {
                            this.ratio = parseFloat(data.image_red_ratio / 100)
                        } else {
                            this.ratio = parseFloat(data.video_red_ratio / 100)
                        }
                    }
                })
        },
        /**
         * 创建全部表单组件
         */
        createForm(){
            this.schema.fields = [
                {
                    type:'input',
                    modelKey:'money',
                    label:'单个金额',
                    props:{
                        type:'text',
                        placeholder:'0.00',
                        disabled: this.red_id !== 0
                    },
                    rules:{
                        required:true,
                        type:'number',
                        pattern:/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
                    },
                    messages:{
                        required:'请输入红包金额',
                        type:'请输入正确的红包金额',
                        pattern:'请输入正确的红包金额'
                    }
                },
                {
                    type: 'radio-group',
                    modelKey: 'type',
                    props:{
                        horizontal:true,
                        options:[
                            {label:'普通红包',value:1,disabled: this.red_id !== 0},
                            {label:'手气红包',value:2,disabled: this.red_id !== 0}
                        ]
                    },
                    rules:{
                        required:true
                    }
                },
                {
                    type:'input',
                    modelKey:'number',
                    label:'红包个数',
                    props:{
                        type:'text',
                        placeholder:'填写个数',
                        disabled: this.red_id !== 0
                    },
                    rules:{
                        required:true,
                        type:'number',
                        max:1000000,
                        min:1,
                        pattern:/^\d+$/
                    },
                    messages:{
                        required:'请输入红包个数',
                        type:'请输入正确的红包个数',
                        max:'红包个数不能超过一百万',
                        min:'请输入正确的红包个数',
                        pattern:'请输入正确的红包个数'
                    }
                },
                {
                    type:'input',
                    modelKey:'title',
                    label:'标题',
                    props:{
                        type:'text',
                        placeholder:'红包标题'
                    },
                    rules:{
                        required:true,
                        max:10,
                        min:1
                    },
                    messages:{
                        required:'请输入红包标题',
                        max:'标题长度不能大于30',
                        min:'请输入红包标题'
                    }
                },
                {
                    type: 'radio-group',
                    modelKey: 'send_coupon',
                    label: '红包卡券',
                    props:{
                        horizontal:true,
                        options:[
                            {label:'关闭',value:0},
                            {label:'开启',value:1}
                        ]
                    }
                },
                {
                    type: 'radio-group',
                    modelKey: 'red_form',
                    label: '填表开红包',
                    props:{
                        horizontal:true,
                        options:[
                            {label:'关闭',value:0},
                            {label:'开启',value:1}
                        ]
                    }
                },
                {
                    type: 'radio-group',
                    modelKey: 'question',
                    label: '答题领包',
                    props:{
                        horizontal:true,
                        colNum:2,
                        options:[
                            {label:'关闭',value:0},
                            {label:'选择题',value:1},
                            {label:'问答题',value:2}
                        ]
                    }
                },
                {
                    type: 'radio-group',
                    modelKey: 'time_type',
                    props:{
                        horizontal:true,
                        options:[
                            {label:'永久有效',value:1},
                            {label:'限制时间',value:2}
                        ]
                    }
                },
                {
                    type:'radio-group',
                    modelKey:'area_type',
                    label:'区域限制',
                    props: {
                        horizontal:true,
                        colNum:2,
                        options:[
                            {
                                label: '不限制',
                                value: 0
                            },
                            {
                                label: '省级',
                                value: 1
                            },
                            {
                                label:'市级',
                                value:2
                            },
                            {
                                label:'区(县)',
                                value:3
                            }
                        ]
                    }
                },
                {
                    type: 'checkbox',
                    modelKey: 'award',
                    props:{
                        option: {
                            label: '使用助力红包'
                        }
                    }
                },
                {
                    type: FormLink,
                    modelKey: 'link',
                    label: '推广链接'
                }
            ]
        },
        /**
         * 插入红包卡券选择器
         */
        pushCouponForm() {
            let position = this.getTogglePosition("send_coupon")
            this.model.coupon = ""
            if(this.model.send_coupon === 0 && this.schema.fields[position].modelKey === 'coupon'){
                this.schema.fields.splice(position,1)
            } else {
                this.schema.fields.splice(position,0,{
                    type: FormCoupon,
                    modelKey: 'coupon'
                })
            }
        },
        /**
         * 插入红包表单
         */
        pushRedForm() {
            let position = this.getTogglePosition("red_form")
            this.model.red_form_id = ""
            if(this.model.red_form === 0 && this.schema.fields[position].modelKey === 'red_form_id'){
                this.schema.fields.splice(position,1)
            } else {
                this.schema.fields.splice(position,0,{
                    type: FormManage,
                    modelKey: 'red_form_id',
                    label: '表单名字'
                })
            }
        },
        /**
         * 插入图片红包所需组件
         */
        pushImageRedForm(){
            let position = this.getTogglePosition("title")
            this.schema.fields.splice(position,0,{
                type:FormMedia,
                modelKey:'media',
                label: '红包图片',
                props: {
                    number:9
                },
                events: {
                  remove:(index)=>{
                      this.model.media.splice(index,1)
                  }
                },
                rules:{
                    required:true
                }
            })
        },
        /**
         * 插入视频红包所需form组件
         */
        pushVideoRedForm(){
            let position = this.getTogglePosition("title")
            this.schema.fields.splice(position,0,{
                type:FormMedia,
                modelKey:'media',
                label: '红包视频',
                props: {
                    number:1,
                    type: 'video'
                },
                events: {
                    remove:(index)=>{
                        this.model.media.splice(index,1)
                    }
                },
                rules:{
                    required:true
                }
            })
        },
        /**
         * 红包创建取消时间组件
         */
        toggleTimeForm(is_show){
            let position = this.getTogglePosition("time_type")
            if(is_show) {
                this.schema.fields.splice(position,0,{
                    type: FormTime,
                    modelKey: 'time',
                    label:'红包有效期'
                })
            } else {
                if(this.schema.fields[position].modelKey === 'time'){
                    this.schema.fields.splice(position,1)
                }
            }
        },
        /**
         * 创建取消区域组件
         */
        toggleAreaForm(area_type) {
            this.model.area = ""
           let position = this.getTogglePosition("area_type")
            if(this.schema.fields[position].modelKey === 'area'){
                this.schema.fields.splice(position,1)
            }
           if(area_type !== 0){
                this.schema.fields.splice(position,0,{
                    type: FormArea,
                    modelKey: 'area',
                    label: '红包地区',
                    props: {
                        level: area_type
                    },
                    rules: {
                        required: true
                    },
                    messages: {
                        required: '请设置红包限制区域'
                    }
                })
           }
        },
        /**
         * 创建取消问答红包表单组件
         */
        toggleQuestionForm(){
            let question = this.model.question
            let position = this.getTogglePosition("question")
            if(this.schema.fields[position].modelKey === 'choice_question'
                ||
               this.schema.fields[position].modelKey === 'answer_question'
            ){
                this.schema.fields.splice(position,1)
            }
            if(question === 1) {
                this.schema.fields.splice(position,0,{
                    type: FormChoiceQuestion,
                    modelKey: 'choice_question'
                })
            } else if(question === 2){
                this.schema.fields.splice(position,0,{
                    type: FormAnwserQuestion,
                    modelKey: 'answer_question'
                })
            }
        },
        /**
         * 传入取消表单组件时获取插入取消的数组下标位置
         * @param model_key 表单的model值
         * @returns {number}
         */
        getTogglePosition(model_key){
            let position = 0
            for(position=0;position<this.schema.fields.length;position++) {
                if(this.schema.fields[position].modelKey === model_key){
                    break;
                }
            }
            return position+1
        },
        /**
         * 提交红包
         */
        submit() {
            if(!this.submitCheck()) return false;
            this.publishing = true
            let action = this.red_id === 0 ? 'sendRed' : 'editRed'
            this.$post(action, {
                data: this.send_data,
                red_id: this.red_id
            })
                .then((res) => {
                    if(this.red_id) {
                        this.editAfter(res)
                    } else {
                        this.sendAfter(res)
                    }
                });
        },
        /**
         * 发红包之后处理
         */
        sendAfter(res){
            let {code, data, err_msg, pay_params} = res.data
            if(code === 0) {
                this.red_id = data
                store.commit("enter_red", data)
                if(pay_params === undefined) {
                    this.publishing = false
                    this.$router.go(-1)
                } else {
                    if(process.env.NODE_ENV === 'development'){
                        this.wxPaySuccess()
                    } else {
                        this.wxPay(pay_params)
                    }
                }
            } else {
                this.$createToast({
                    time: 1500,
                    txt: err_msg ? err_msg : '发红包失败',
                    type:'error',
                    mask:true
                }).show();
                this.publishing = false;
            }
        },
        /**
         * 修改红包后处理
         */
        editAfter(res){
            let {code} = res.data
            this.publishing = false
            if(code === 0) {
                this.$createToast({
                    time: 1500,
                    txt: '修改成功',
                    mask: true,
                    type: 'correct',
                }).show()
            } else {
                this.$createToast({
                    time: 1500,
                    txt: '修改失败',
                    mask: true,
                    type: 'error',
                }).show()
            }
        },
        /**
         * 提交验证
         */
        submitCheck() {
            if(this.publishing) return;
            // 红包总额最低金额验证
            if(this.setting.low_red_money > 0 && this.total < this.setting.low_red_money) {
                this.$createToast({
                    time: 2000,
                    txt: '红包总额不能低于'+ this.setting.low_red_money.toFixed(2) + '元',
                    type:"error",
                    mask:true
                }).show();
                return false;
            }
            // 手气红包时单个红包金额不能小于0.01元
            if(this.model.type === 2) {
                // 手气红包时单个红包金额不能小于0.01元
                if(parseFloat(this.model.money) / parseInt(this.model.number) < 0.01){
                    this.$createToast({
                        time: 2000,
                        txt: '单个红包金额不能小于0.01元',
                        type: 'error'
                    }).show()
                    return false;
                }
                //手气红包时，红包数量必须大于1
                if(parseInt(this.model.number) <= 1) {
                    this.$createToast({
                        time: 2000,
                        txt: '手气红包个数必须大于1',
                        type:"error",
                        mask:true
                    }).show();
                    return false;
                }
            }
            // 验证卡券
            if(this.model.send_coupon === 1 && this.model.coupon === ""){
                this.$createToast({
                    time: 2000,
                    txt: '请选择卡券',
                    type: 'error'
                }).show()
                return false;
            }
            // 验证答题
            if(this.model.question !== 0) {
                if(this.model.question === 1) {
                    if(this.model.choice_question[0].trim() === '') {
                        this.$createToast({
                            time: 2000,
                            txt: '请设置答题内容',
                            type: 'error'
                        }).show()
                        return false;
                    }
                    for(let i=0;i<this.model.choice_question.length;i++) {
                        if(i > 1) {
                            if(this.model.choice_question[i].trim() === '') {
                                this.$createToast({
                                    time: 2000,
                                    txt: '请设置答题选项',
                                    type: 'error'
                                }).show()
                                return false;
                            }
                        }
                    }
                } else {
                    if(this.model.answer_question[0].trim() === '') {
                        this.$createToast({
                            time: 2000,
                            txt: '请输入答题内容',
                            type: 'error'
                        }).show()
                        return false;
                    }
                    if(this.model.answer_question[1].trim() === '') {
                        this.$createToast({
                            time: 2000,
                            txt: '请输入正确答案',
                            type: 'error'
                        }).show()
                        return false;
                    }
                }
            }
            // 验证红包时间
            if(this.model.time_type === 2) {
                if(!this.model.time.end || !this.model.time.start) {
                    this.$createToast({
                        time: 2000,
                        txt: '请设置红包时间',
                        type: 'error'
                    }).show()
                    return false;
                }
                if(this.model.time.end <= this.model.time.start) {
                    this.$createToast({
                        time: 2000,
                        txt: '红包结束时间必须大于开始时间',
                        type: 'error'
                    }).show()
                    return false;
                }
            }
            return true;
        },
        /**
         * 微信支付
         */
        wxPay(params) {
            this.$wx.chooseWXPay({
                timestamp: params.timeStamp,
                nonceStr: params.nonceStr,
                package: params.package,
                signType: params.signType,
                paySign: params.paySign,
                success: ()=>{
                    this.wxPaySuccess()
                },
                cancel: () => {
                    this.wxPayFail()
                },
                fail:()=>{
                    this.wxPayFail()
                },
                complete: (res)=>{
                    if(res.errMsg === 'chooseWXPay:cancel'){
                        this.publishing = false;
                    }
                }
            });
        },
        /**
         * 发红包微信支付成功
         */
        wxPaySuccess() {
            this.$post("sendRed/wxPaySuccess",{
                red_id: this.red_id
            })
                .then((res) => {
                    this.publishing = false
                    let code = res.data.code
                    if(code === 0) {
                        this.$router.go(-1)
                    } else {
                        let err_msg = ''
                        this.red_id = 0
                        if(code === 103) {
                            err_msg = "发红包失败，请联系管理员"
                        } else {
                            err_msg = "支付异常，请联系管理员"
                        }
                        this.$createToast({
                            time: 1500,
                            txt: err_msg,
                            type:'error',
                            mask:true
                        }).show();
                    }
                });
        },
        /**
         * 发红包支付失败
         */
        wxPayFail() {
            this.$createToast({
                time: 1500,
                txt: '发红包失败',
                type:'error',
                mask:true,
                onTimeout: () => {
                    this.publishing = false
                    this.$post("sendRed/wxPayFail",{
                        red_id: this.red_id
                    })
                        .then(() => {
                            this.red_id = 0
                        });
                }
            }).show();
        },
        /**
         * 验证发红包权限
         */
        checkAccess(){
            return this.$get("red/checkAccess")
                .then((res) => {
                    let {code, data} = res.data
                    if(code === 0) {
                        this.access = data
                    }
                })
        },
        /**
         * 提示关注公众号
         */
        attentionDialog() {
            this.$get("weChat/sendAttention")
                .then((res) => {
                    let {code,data} = res.data
                    if(code === 0 && data) {
                        let attention = this.$createAttention({
                            is_show: true,
                            onClose: () => {
                                attention.remove()
                            }
                        })
                    }
                })
        },
        /**
         * 获取红包相关配置
         */
        getSetting() {
            this.$get('setting/find')
                .then((res) => {
                    let { code, data } = res.data
                    if (!code) {
                        this.setting = {
                            low_red_money: parseFloat(data.low_red_money)
                        }
                    }
                })
        },
        /**
         * 显示追加红包区域
         */
        showAddTo() {
            this.addTo.show = true
        },
        /**
         * 追加红包成功
         */
        addToSuccess(res) {
            let { number, money } = res
            this.model.number += parseInt(number)
            if(money){
                let sum_money = parseFloat(this.model.money) + parseFloat(money)
                this.model.money = sum_money.toFixed(2)
            }
        }
    }
}
</script>

<style scoped lang="less" src="./send.less"></style>
